package com.hzz.service.dsync;

import com.alibaba.fastjson.JSONObject;
import com.hzz.api.report.*;
import com.hzz.dto.dsync.ErReportPageResultDto;
import com.hzz.dto.report.*;
import com.hzz.framework.Response;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.DateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@Data
public class ErReportTaskDSync extends BaseDSync {
    @Value("${dsync.erReport.enabled:true}")
    Boolean syncEnabled;
    @Value("${dsync.erReport.xbOnePage}")
    String xbOnePageApi;
    @Value("${dsync.erReport.xbTwoPage}")
    String xbTwoPageApi;
    @Value("${dsync.erReport.xbThreePage}")
    String xbThreePageApi;
    @Value("${dsync.erReport.monthSummaryPage}")
    String monthSummaryPageApi;
    @Value("${dsync.erReport.briefPage}")
    String briefPageApi;
    @Value("${dsync.erReport.xdOnePage}")
    String xdOnePageApi;
    @Value("${dsync.erReport.xyOnePage}")
    String xyOnePageApi;

    @Autowired
    IReportTendayService reportTendayService;
    @Autowired
    IReportMonthlyService reportMonthlyService;
    @Autowired
    IReportWorkBriefService reportWorkBriefService;
    @Autowired
    IReportBimonthlyService reportBimonthlyService;
    @Autowired
    IReportYearService reportYearService;

    public void xbOnePage() {
        log.info("xbOnePage...");
        Integer pageNum = 0;
        Integer pageSize = 15;
        Integer pageCount = 1;
        ErReportPageResultDto pageDto = null;
        do {
            pageNum++;
            String apiUrl = xbOnePageApi + "?PageIndex=" + pageNum + "&PageSize=" + pageSize;
            try {
                Response response = syncGet("xbOnePageApi" + pageNum, apiUrl);
                pageDto = xbOnePage(apiUrl, response);
                if (pageDto != null) {
                    pageCount = pageDto.getPageCount(pageSize);
                }
                if (response != null && response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                    Thread.sleep(15 * 1000);
                }
            } catch (Exception e) {
                log.error("旬报1,拉取", apiUrl);
                log.error("异常原因", e);
            }
        } while (pageDto != null && pageDto.isHasNextPage(pageNum, pageSize) || pageNum < pageCount);
    }

    public ErReportPageResultDto xbOnePage(String apiUrl, Response response) {
        log.info("xbOnePage...");
        ErReportPageResultDto pageDto = null;
        try {
            log.info("调用:" + apiUrl + " , 反馈:" + response.getCode());
            if (response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取 || response.data == null) {
                return pageDto;
            }
            JSONObject data = (JSONObject) response.data;
            pageDto = data.toJavaObject(ErReportPageResultDto.class);
            if (pageDto == null || pageDto.getPageData() == null) {
                return pageDto;
            }
            List<JSONObject> list = pageDto.getPageData();
            if (list != null) {
                list.forEach(jo -> {
                    try {
                        /*
                          {
                            "id": "7109d72c-647c-42dc-888f-c2f98e2b01d2",
                            "areaname": "内江市",
                            "areacode": "5110",
                            "creator": "谢萍",
                            "create_date": "2020-10-22",
                            "shr": "谭文平",
                            "sdr": "谭文名",
                            "contact": "13356012446",
                            "makepublic": "全面建立湖长制对外宣布情况（宣布时间、主要形式）",
                            "real_date": "2020-10-22"
                          }
                         */
                        log.info("jo:{}", jo);
//                        ReportTendayDto dto = new ReportTendayDto();
//                        dto.setId(jo.getString("id"));
//                        dto.setAreaId(jo.getString("areacode"));
//                        dto.setAreaName(jo.getString("areaname"));
//                        dto.setAreaCode(jo.getString("areacode"));
//                        dto.setReportingDate(DateUtil.parseDate(jo.getString("real_date")));
//                        dto.setTitle(jo.getString("makepublic"));
//                        dto.setInitiateDate(jo.getString("real_date"));
//
//                        reportTendayService.saveOrUpdateData(dto);
                    } catch (Exception e) {
                        log.error("旬报1,入库失败," + apiUrl + e.getMessage());
                    }
                });
            }
        } catch (Exception e) {
            log.error("旬报1拉取", apiUrl);
            log.error("异常原因", e);
        } finally {
            logDSyncAdd(CommonConstant.TASK_拉取_ER_旬报1, apiUrl, response);
        }
        return pageDto;
    }

    public void xbTwoPage() {
        log.info("xbTwoPage...");
        Integer pageNum = 0;
        Integer pageSize = 15;
        Integer pageCount = 1;
        ErReportPageResultDto pageDto = null;
        do {
            pageNum++;
            String apiUrl = xbTwoPageApi + "?PageIndex=" + pageNum + "&PageSize=" + pageSize;
            try {
                Response response = syncGet("xbTwoPageApi" + pageNum, apiUrl);
                pageDto = xbTwoPage(apiUrl, response);
                if (pageDto != null) {
                    pageCount = pageDto.getPageCount(pageSize);
                }
                if (response != null && response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                    Thread.sleep(15 * 1000);
                }
            } catch (Exception e) {
                log.error("旬报2,拉取", apiUrl);
                log.error("异常原因", e);
            }
        } while (pageDto != null && pageDto.isHasNextPage(pageNum, pageSize) || pageNum < pageCount);
    }

    public ErReportPageResultDto xbTwoPage(String apiUrl, Response response) {
        log.info("xbTwoPage...");
        ErReportPageResultDto pageDto = null;
        try {
            log.info("调用:" + apiUrl + " , 反馈:" + response.getCode());
            if (response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取 || response.data == null) {
                return pageDto;
            }
            JSONObject data = (JSONObject) response.data;
            pageDto = data.toJavaObject(ErReportPageResultDto.class);
            if (pageDto == null || pageDto.getPageData() == null) {
                return pageDto;
            }
            List<JSONObject> list = pageDto.getPageData();
            if (list != null) {
                list.forEach(jo -> {
                    try {
                        // {"sdr":"谭文平","haverealen":"26","county_fileshould":16,"village_lakerextension":"false","areacode":"5110","county_filefinish":17,"town_policyshould":0,"town_policyfinish":0,"policyhaveorggmcnt":"20","filehaveorggmcnt":"22","village_riverextension":"true","contact":"13356012446","city_fileshould":12,"city_policyfinish":11,"shdrealen":"25","filenote":"一河一档备注旬报2","id":"355f7367-a80b-4183-903e-0faedbf32124","city_filefinish":13,"create_date":"2020-10-22","city_policyshould":10,"gmcount":"28","creator":"谢萍","policynote":"一河一策备注旬报2","areaname":"内江市","shdreacnt":"23","county_policyfinish":15,"havereacnt":"24","policyreportgmcnt":19,"real_date":"2020-10-22","county_policyshould":14,"filereportgmcnt":"21","village_hirepoor":18,"punishcount":"27","town_filefinish":0,"town_fileshould":0,"shr":"谭文平"}
                        log.info("jo:{}", jo);
//                        ReportTendayDto dto = new ReportTendayDto();
//                        reportTendayService.saveOrUpdateData(dto);
                    } catch (Exception e) {
                        log.error("旬报2,入库失败," + apiUrl + e.getMessage());
                    }
                });
            }
        } catch (Exception e) {
            log.error("旬报2拉取", apiUrl);
            log.error("异常原因", e);
        } finally {
            logDSyncAdd(CommonConstant.TASK_拉取_ER_旬报2, apiUrl, response);
        }
        return pageDto;
    }

    public void xbThreePage() {
        log.info("xbThreePage...");
        Integer pageNum = 0;
        Integer pageSize = 15;
        Integer pageCount = 1;
        ErReportPageResultDto pageDto = null;
        do {
            pageNum++;
            String apiUrl = xbThreePageApi + "?PageIndex=" + pageNum + "&PageSize=" + pageSize;
            try {
                Response response = syncGet("xbThreePageApi" + pageNum, apiUrl);
                pageDto = xbThreePage(apiUrl, response);
                if (pageDto != null) {
                    pageCount = pageDto.getPageCount(pageSize);
                }
                if (response != null && response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                    Thread.sleep(15 * 1000);
                }
            } catch (Exception e) {
                log.error("旬报3,拉取", apiUrl);
                log.error("异常原因", e);
            }
        } while (pageDto != null && pageDto.isHasNextPage(pageNum, pageSize) || pageNum < pageCount);
    }

    public ErReportPageResultDto xbThreePage(String apiUrl, Response response) {
        log.info("xbThreePage...");
        ErReportPageResultDto pageDto = null;
        try {
            log.info("调用:" + apiUrl + " , 反馈:" + response.getCode());
            if (response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取 || response.data == null) {
                return pageDto;
            }
            JSONObject data = (JSONObject) response.data;
            pageDto = data.toJavaObject(ErReportPageResultDto.class);
            if (pageDto == null || pageDto.getPageData() == null) {
                return pageDto;
            }
            List<JSONObject> list = pageDto.getPageData();
            if (list != null) {
                list.forEach(jo -> {
                    try {
                        log.info("jo:{}", jo);
                        // {"sdr":"李四","creator":"超级管理员","areaname":"内江市","contact":"15884526946","id":"016552a7-aea0-42c1-ac43-2a419acd3ccb","create_date":"2021-03-26","shr":"张三","areacode":"5110","real_date":"2021-03-26"}
//                        ReportTendayDto dto = new ReportTendayDto();
//                        reportTendayService.saveOrUpdateData(dto);
                    } catch (Exception e) {
                        log.error("旬报3,入库失败," + apiUrl + e.getMessage());
                    }
                });
            }
        } catch (Exception e) {
            log.error("旬报3,拉取", apiUrl);
            log.error("异常原因", e);
        } finally {
            logDSyncAdd(CommonConstant.TASK_拉取_ER_旬报3, apiUrl, response);
        }
        return pageDto;
    }

    public void monthSummaryPage() {
        log.info("monthSummaryPage...");
        Integer pageNum = 0;
        Integer pageSize = 15;
        Integer pageCount = 1;
        ErReportPageResultDto pageDto = null;
        do {
            pageNum++;
            String apiUrl = monthSummaryPageApi + "?PageIndex=" + pageNum + "&PageSize=" + pageSize;
            try {
                Response response = syncGet("monthSummaryPageApi" + pageNum, apiUrl);
                pageDto = monthSummaryPage(apiUrl, response);
                if (pageDto != null) {
                    pageCount = pageDto.getPageCount(pageSize);
                }
                if (response != null && response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                    Thread.sleep(15 * 1000);
                }
            } catch (Exception e) {
                log.error("月小结报,拉取", apiUrl);
                log.error("异常原因", e);
            }
        } while (pageDto != null && pageDto.isHasNextPage(pageNum, pageSize) || pageNum < pageCount);
    }

    public ErReportPageResultDto monthSummaryPage(String apiUrl, Response response) {
        log.info("monthSummaryPage...");
        ErReportPageResultDto pageDto = null;
        try {
            log.info("调用:" + apiUrl + " , 反馈:" + response.getCode());
            if (response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取 || response.data == null) {
                return pageDto;
            }
            JSONObject data = (JSONObject) response.data;
            pageDto = data.toJavaObject(ErReportPageResultDto.class);
            if (pageDto == null || pageDto.getPageData() == null) {
                return pageDto;
            }
            List<JSONObject> list = pageDto.getPageData();
            if (list != null) {
                list.forEach(jo -> {
                    try {
                        log.info("jo:{}", jo);
                        // {"affixnameword":"配置管理基线申请单(组织级).doc","creator":"谢萍","areaname":"内江市","affixnamepdf":"CMMI各过程域的体系建立要点.pdf","affixurlpdf":"20201022144756.pdf","batch":"2020年2季度","issupplement":"false","title":"202002季度季报","areacode":"5110","real_date":"2020-10-22","affixurlword":"20201022144210.doc","contact":"13356012446","notice_department":"内江市河长办公室","id":"d6fce2a2-b7e8-41b0-a29b-6c4b9bda9566","create_date":"2020-10-22"}
//                        ReportMonthlyDto dto = new ReportMonthlyDto();
//                        reportMonthlyService.saveOrUpdateData(dto);
                    } catch (Exception e) {
                        log.error("月小结报,入库失败," + apiUrl + e.getMessage());
                    }
                });
            }
        } catch (Exception e) {
            log.error("月小结报,拉取", apiUrl);
            log.error("异常原因", e);
        } finally {
            logDSyncAdd(CommonConstant.TASK_拉取_ER_月小结报, apiUrl, response);
        }
        return pageDto;
    }

    public void briefPage() {
        log.info("briefPage...");
        Integer pageNum = 0;
        Integer pageSize = 15;
        Integer pageCount = 1;
        ErReportPageResultDto pageDto = null;
        do {
            pageNum++;
            String apiUrl = briefPageApi + "?PageIndex=" + pageNum + "&PageSize=" + pageSize;
            try {
                Response response = syncGet("briefPageApi" + pageNum, apiUrl);
                pageDto = briefPage(apiUrl, response);
                if (pageDto != null) {
                    pageCount = pageDto.getPageCount(pageSize);
                }
                if (response != null && response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                    Thread.sleep(15 * 1000);
                }
            } catch (Exception e) {
                log.error("工作简报,拉取", apiUrl);
                log.error("异常原因", e);
            }
        } while (pageDto != null && pageDto.isHasNextPage(pageNum, pageSize) || pageNum < pageCount);
    }

    public ErReportPageResultDto briefPage(String apiUrl, Response response) {
        log.info("briefPage...");
        ErReportPageResultDto pageDto = null;
        try {
            log.info("调用:" + apiUrl + " , 反馈:" + response.getCode());
            if (response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取 || response.data == null) {
                return pageDto;
            }
            JSONObject data = (JSONObject) response.data;
            pageDto = data.toJavaObject(ErReportPageResultDto.class);
            if (pageDto == null || pageDto.getPageData() == null) {
                return pageDto;
            }
            List<JSONObject> list = pageDto.getPageData();
            if (list != null) {
                list.forEach(jo -> {
                    try {
                        log.info("jo:{}", jo);
                        // {"creator":"超级管理员","areaname":"内江市","affixurl":"20200702154735.pdf","filenumber":"2020年7期","filedate":"2019-12-07","affixname":"up (1).pdf","fileorganization":"内江市东兴区河（库）长制办公室","title":"东兴区召开长江流域重点水域禁捕暨渔民退捕安置保障工作领导小组第一次会议","areacode":"5110","contact":"15884526946","notice_department":"内江市河长办公室","id":"c2c6a812-14ff-4df6-b747-04a5a753b975","create_date":"2020-07-02","srname":"01,02"}
//                        ReportWorkBriefDto dto = new ReportWorkBriefDto();
//                        reportWorkBriefService.saveOrUpdateData(dto);
                    } catch (Exception e) {
                        log.error("工作简报,入库失败," + apiUrl + e.getMessage());
                    }
                });
            }
        } catch (Exception e) {
            log.error("工作简报,拉取", apiUrl);
            log.error("异常原因", e);
        } finally {
            logDSyncAdd(CommonConstant.TASK_拉取_ER_工作简报, apiUrl, response);
        }
        return pageDto;
    }

    public void xdOnePage() {
        log.info("xdOnePage...");
        Integer pageNum = 0;
        Integer pageSize = 15;
        Integer pageCount = 1;
        ErReportPageResultDto pageDto = null;
        do {
            pageNum++;
            String apiUrl = xdOnePageApi + "?PageIndex=" + pageNum + "&PageSize=" + pageSize;
            try {
                Response response = syncGet("xdOnePageApi" + pageNum, apiUrl);
                pageDto = xdOnePage(apiUrl, response);
                if (pageDto != null) {
                    pageCount = pageDto.getPageCount(pageSize);
                }
                if (response != null && response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                    Thread.sleep(15 * 1000);
                }
            } catch (Exception e) {
                log.error("双月报,拉取", apiUrl);
                log.error("异常原因", e);
            }
        } while (pageDto != null && pageDto.isHasNextPage(pageNum, pageSize) || pageNum < pageCount);
    }

    public ErReportPageResultDto xdOnePage(String apiUrl, Response response) {
        log.info("xdOnePage...");
        ErReportPageResultDto pageDto = null;
        try {
            log.info("调用:" + apiUrl + " , 反馈:" + response.getCode());
            if (response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取 || response.data == null) {
                return pageDto;
            }
            JSONObject data = (JSONObject) response.data;
            pageDto = data.toJavaObject(ErReportPageResultDto.class);
            if (pageDto == null || pageDto.getPageData() == null) {
                return pageDto;
            }
            List<JSONObject> list = pageDto.getPageData();
            if (list != null) {
                list.forEach(jo -> {
                    try {
                        log.info("jo:{}", jo);
//                        ReportBimonthlyDto dto = new ReportBimonthlyDto();
//                        reportBimonthlyService.saveOrUpdateData(dto);
                    } catch (Exception e) {
                        log.error("双月报,入库失败," + apiUrl + e.getMessage());
                    }
                });
            }
        } catch (Exception e) {
            log.error("双月报,拉取", apiUrl);
            log.error("异常原因", e);
        } finally {
            logDSyncAdd(CommonConstant.TASK_拉取_ER_双月报, apiUrl, response);
        }
        return pageDto;
    }

    public void xyOnePage() {
        log.info("xyOnePage...");
        Integer pageNum = 0;
        Integer pageSize = 15;
        Integer pageCount = 1;
        ErReportPageResultDto pageDto = null;
        do {
            pageNum++;
            String apiUrl = xyOnePageApi + "?PageIndex=" + pageNum + "&PageSize=" + pageSize;
            try {
                Response response = syncGet("xyOnePageApi" + pageNum, apiUrl);
                pageDto = xyOnePage(apiUrl, response);
                if (pageDto != null) {
                    pageCount = pageDto.getPageCount(pageSize);
                }
                if (response != null && response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                    Thread.sleep(15 * 1000);
                }
            } catch (Exception e) {
                log.error("年报,拉取", apiUrl);
                log.error("异常原因", e);
            }
        } while (pageDto != null && pageDto.isHasNextPage(pageNum, pageSize) || pageNum < pageCount);
    }

    public ErReportPageResultDto xyOnePage(String apiUrl, Response response) {
        log.info("xyOnePage...");
        ErReportPageResultDto pageDto = null;
        try {
            log.info("调用:" + apiUrl + " , 反馈:" + response.getCode());
            if (response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取 || response.data == null) {
                return pageDto;
            }
            JSONObject data = (JSONObject) response.data;
            pageDto = data.toJavaObject(ErReportPageResultDto.class);
            if (pageDto == null || pageDto.getPageData() == null) {
                return pageDto;
            }
            List<JSONObject> list = pageDto.getPageData();
            if (list != null) {
                list.forEach(jo -> {
                    try {
                        log.info("jo:{}", jo);
//                        ReportYearDto dto = new ReportYearDto();
//                        reportYearService.saveOrUpdateData(dto);
                    } catch (Exception e) {
                        log.error("年报,入库失败," + apiUrl + e.getMessage());
                    }
                });
            }
        } catch (Exception e) {
            log.error("年报,拉取", apiUrl);
            log.error("异常原因", e);
        } finally {
            logDSyncAdd(CommonConstant.TASK_拉取_ER_年报, apiUrl, response);
        }
        return pageDto;
    }

}
